package com.cgwx.systemservice.service.impl;

import com.cgwx.springsecurity.custom.CustomUser;
import com.cgwx.springsecurity.entity.SysUser;
import com.cgwx.systemservice.service.SysMenuService;
import com.cgwx.systemservice.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import com.cgwx.springsecurity.service.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author GaoWei
 * @Date 2023/10/21 - 11:29
 */
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysMenuService sysMenuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserService.getUserInfoByUserName(username);
        if(sysUser == null){
            throw new UsernameNotFoundException("用户不存在");
        }
        if(sysUser.getStatus() == 0){
            throw new RuntimeException("用户已经被禁用");
        }
//        根据userid查询操作权限数据
        List<String> userPermList = sysMenuService.getUserButtonList(sysUser.getId());
//        转换为Security要求的格式数据
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (String userPerm : userPermList) {
            authorities.add(new SimpleGrantedAuthority(userPerm.trim()));
        }
        return new CustomUser(sysUser, authorities);
    }
}
